<?php
namespace app\app\model;
use think\Validate;
class Send extends \think\Model
{
	public static $sms_config = [
		'appkey'		=> '',//阿里大于APPKEY
		'secretKey' 	=> '',//阿里大于secretKey
		'FreeSignName' 	=> '',//短信签名
	];
	public function sms($data=[])
	{
		$validate = new Validate([
			['content','require|array','参数必填|参数必须为数组'],
			['phone','require|/1[34578]{1}\d{9}$/','手机号错误|手机号错误'],
			//['template','require','模板id错误'],
		]);
		if (!$validate->check($data)) {
			return $validate->getError();
		}
		Vendor("alidayu.aliyun-php-sdk-core.Config");
		Vendor("alidayu.Dysmsapi.Request/V20170525/SendSmsRequest");
		//$config = self::$sms_config;
		$config = db('sms_config')->where('id',1)->find();
		//此处需要替换成自己的AK信息
		$accessKeyId = $config['appkey'];
		$accessKeySecret = $config['appsecret'];
		//短信API产品名
		$product = "Dysmsapi";
		//短信API产品域名
		$domain = "dysmsapi.aliyuncs.com";
		//暂时不支持多Region
		$region = "cn-hangzhou";

		//初始化访问的acsCleint
		$profile = \DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
		\DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
		$acsClient= new \DefaultAcsClient($profile);

		$request = new \Dysmsapi\Request\V20170525\SendSmsRequest;
		//必填-短信接收号码
		$request->setPhoneNumbers($data['phone']);
		//必填-短信签名
		$request->setSignName($config['sign']);
		//必填-短信模板Code
		$request->setTemplateCode($config['template']);
		//选填-假如模板中存在变量需要替换则为必填(JSON格式)
		$request->setTemplateParam(json_encode($data['content']));
		//选填-发送短信流水号
		$request->setOutId("1234");

		//发起访问请求
		$acsResponse = $acsClient->getAcsResponse($request);
        /*if($acsResponse->Message == "OK" && $acsResponse->Code == "OK"){

            $return['code'] = 1;
            $insert['time'] = time();
            $insert['phone'] = $data['phone'];
            $insert['content'] = json_encode($data['content']);
            $insert['template'] = $config['template'];
            db('sms_record')->insert($insert);
		}else{*/
			$return['code'] = 2;
			$return['msg'] = $acsResponse->Message;
		//}
		return json($return);
	}

	private function _simplexml_to_array($obj)
	{
		if(count($obj) >= 1){
			$result = $keys = [];
			foreach($obj as $key=>$value){
				isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1);
				if( $keys[$key] == 1 ){
					$result[$key] = $this->_simplexml_to_array($value);
				}elseif( $keys[$key] == 2 ){
					$result[$key] = [$result[$key], $this->_simplexml_to_array($value)];
				}else if( $keys[$key] > 2 ){
					$result[$key][] = $this->_simplexml_to_array($value);
				}
			}
			return $result;
		}else if(count($obj) == 0){
			return (string)$obj;
		}
	}
}
?>